//
//  MyNewsViewController.m
//  安好
//
//  Created by 马晓良 on 14-12-10.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "MyNewsViewController.h"
#import "SysMessCell.h"
#import "SubscibeDetailViewController.h"
#import "SubscibeModel.h"
#import "SystemSubscibeCell.h"
@interface MyNewsViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *myNewsTableView;
// 存放数据
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger newsPage;
@end

@implementation MyNewsViewController

- (NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        self.dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myNewsTableView.dataSource = self;
    self.myNewsTableView.delegate = self;
    self.navigationItem.title = @"收藏的新闻";
    self.myNewsTableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.newsPage = 1;
    [self loadData];
    [self setNaviBarAttribute];
    [self.myNewsTableView addFooterWithTarget:self action:@selector(loadData)];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 设置naviBar 并实现左右naviBar button方法 -
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
}


/**
 *  返回主页面
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - tableview delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (kScreenWidth == 414) {
        return 108;
    }else{
        return 90;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";
//    SysMessCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//    if(!cell)
//    {
//        cell = [[[NSBundle mainBundle] loadNibNamed:@"SysMessCell" owner:self options:nil] lastObject];
//    }
//    cell.titleLabel.text = [[self.dataArray objectAtIndex:indexPath.row] objectForKey:@"title"];
//    cell.contentLabel.text = [[self.dataArray objectAtIndex:indexPath.row] objectForKey:@"content"];
//    cell.nImageView.hidden = YES;
    
    SystemSubscibeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        if (kScreenWidth == 414) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"SystemSubscibeCell" owner:self options:nil] lastObject];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"SystemSubscibeCell" owner:self options:nil] firstObject];
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    SubscibeModel *model = [self.dataArray objectAtIndex:indexPath.row];
    cell.subscibeTitleLabel.text = model.titleForSubscibe;
    cell.subscibeDetailLabel.text = model.catnameForSubscibe;
    [cell.userPhotoImageView setImageWithURL:[NSURL URLWithString:model.picForSubscibe] placeholderImage:[UIImage imageNamed:@"subscibe_default"]];
    cell.isNewImageView.hidden = YES;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SubscibeDetailViewController * subcibeVC = [[SubscibeDetailViewController alloc]init];
    SubscibeModel *model = [self.dataArray objectAtIndex:indexPath.row];
    subcibeVC.subscibeModel = model;
    subcibeVC.subscibeViewController = self;
    [self.navigationController pushViewController:subcibeVC animated:YES];
}

- (void)loadData
{
    [self showActionView];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:@"6" forKey:@"type"];
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)self.newsPage] forKey:@"page"];
    
    MyNSLog("%@",dict);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@collection/list/",kBaseURL] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            [self.myNewsTableView footerEndRefreshing];
        }else{
            NSArray *jsonDictArr = [[responseObject objectForKey:@"data"] isEqual:[NSNull null]]?nil:[responseObject objectForKey:@"data"];
            
            MyNSLog("%@", jsonDictArr);
            if (jsonDictArr != nil) {
                self.newsPage++;
                for (NSDictionary * dic in jsonDictArr){
                     SubscibeModel *model = [[SubscibeModel alloc] initWithDict:dic];
                    [self.dataArray addObject:model];
                }
                [self.myNewsTableView reloadData];
            }else if ([jsonDictArr count] < 20){
                [self.myNewsTableView footerEndRefreshing];
            }else{
                if (self.newsPage > 1) {
                    MyNSLog("下拉无数据");
                }
            }
        }
        [self.myNewsTableView footerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        [self.myNewsTableView footerEndRefreshing];
    }];
    
}


- (void)updateIsCollectionWithNid:(NSString *)nid andIsCollection:(NSInteger)isCollection{
    for (NSInteger i = 0; i < self.dataArray.count; i++) {
        SubscibeModel *model = [self.dataArray objectAtIndex:i];
        if ([model.nidForSubscibe integerValue] == [nid integerValue]) {
            if (isCollection == 0) {
                [self.dataArray removeObjectAtIndex:i];
                [self.myNewsTableView reloadData];
            }
            break;
        }
    }
    [super updateIsCollectionWithNid:nid andIsCollection:isCollection];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
